package com.whl.mybatis.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 驼峰法-下划线互转
 */
public class UnderlineCamelUtils {

	/**
	 * 下划线转驼峰法
	 * @param underline 源字符串
	 * @param smallCamel 大小驼峰,是否为小驼峰
	 * @return 转换后的字符串
	 */
	public static String underline2Camel(String underline, boolean smallCamel) {
		if (underline == null || "".equals(underline)) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		Pattern pattern = Pattern.compile("([A-Za-z\\d]+)(_)?");
		Matcher matcher = pattern.matcher(underline);
		while (matcher.find()) {
			String word = matcher.group();
			sb.append(smallCamel && matcher.start() == 0 ? Character.toLowerCase(word.charAt(0))
					: Character.toUpperCase(word.charAt(0)));
			int index = word.lastIndexOf('_');
			if (index > 0) {
				sb.append(word.substring(1, index).toLowerCase());
			} else {
				sb.append(word.substring(1).toLowerCase());
			}
		}
		return sb.toString();
	}

	/**
	 * 驼峰法转下划线
	 * @param camel 源字符串
	 * @return 转换后的字符串
	 */
	public static String camel2underline(String camel, boolean toUpperCase) {
		if (camel == null || "".equals(camel)) {
			return "";
		}
		camel = String.valueOf(camel.charAt(0)).toUpperCase().concat(camel.substring(1));
		StringBuilder sb = new StringBuilder();
		Pattern pattern = Pattern.compile("[A-Z]([a-z\\d]+)?");
		Matcher matcher = pattern.matcher(camel);
		while (matcher.find()) {
			String word = matcher.group();
			sb.append(word);
			sb.append(matcher.end() == camel.length() ? "" : "_");
		}
		if (toUpperCase) {
			return sb.toString().toUpperCase();
		}
		return sb.toString().toLowerCase();
	}
	
	public static void main(String[] args) {
		System.out.println(camel2underline("default_", false));
	}

}